package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.excel.NAVPerShs;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.excel.NAVPerShsRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class NAVPerShsListener extends AnalysisEventListener<NAVPerShs> {
    Logger logger = LoggerFactory.getLogger(NAVPerShsListener.class);
    private static final int BATCH_COUNT = 3000;
    List<NAVPerShs> list=new ArrayList<NAVPerShs>();

    private NAVPerShsRepo navPerShsRepo;
    private String head;
    private String name;
    private Date date;

    public NAVPerShsListener(){
    }

    public NAVPerShsListener(NAVPerShsRepo navPerShsRepo, String name, Date date){
        this.navPerShsRepo=navPerShsRepo;
        this.name=name;
        this.date=date;
    }

    @Override
    public void invoke(NAVPerShs data, AnalysisContext analysisContext) {
        data.setHeadTitle(head);
        data.setFundname(name);
        data.setDate(date);
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        logger.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
            logger.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        }
    }

    //读取表头内容
    int x=0;
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        x++;
        if(x==1){
            head=headMap.get(0);
            System.out.println(head);
        }

//        System.out.println("表头："+headMap);
    }
    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData(){
        navPerShsRepo.saveAll(list);
    }
}
